<template>
  <div class="lc_wrap">
    <el-row class="CountreportTabel">
      
      <!-- 左侧树 -->
      <el-col :span="leftWidth">
        <div class="box treeBox">
          <basic-container>
            <lcTree @ready="ready" :deviceType="3"></lcTree>
          </basic-container>
        </div>
      </el-col>

      <!-- 内容 -->
      <el-col :span="rightWidth" class="table-wrapper">
        <overlay @changeTreeBox="changeTreeBox"></overlay>
        <basic-container>

          <!-- 自定义搜索 -->
          <div class="search-tools">
            <div class="search-left">

              <!-- 时 -->
              <div v-if="dateType == 1">
                <el-date-picker
                  v-model="dateTime"
                  type="date"
                  size="small"
                  value-format="yyyy-MM-dd"
                  :picker-options="pickerOption"
                  placeholder="选择日期"
                  :clearable="false">
                </el-date-picker>
                <el-time-select
                  v-model="hourTime"
                  size="small"
                  placeholder="选择时间"
                  :picker-options="{start: '00:00',step: '01:00',end: '23:00'}"
                  :clearable="false"
                  style="margin-left:10px">
                </el-time-select>
              </div>

              <!-- 日 -->
              <div v-if="dateType == 2">
                <el-date-picker
                  v-model="dateTime"
                  type="date"
                  size="small"
                  value-format="yyyy-MM-dd"
                  :picker-options="pickerOption"
                  placeholder="选择日期"
                  :clearable="false">
                </el-date-picker>
              </div>

              <!-- 周 -->
              <div v-if="dateType == 3">
                <el-date-picker
                  v-model="dateTime"
                  type="week"
                  size="small"
                  format="yyyy 第 WW 周"
                  value-format="yyyy-MM-dd"
                  :picker-options="pickerOption"
                  placeholder="选择周"
                  :clearable="false">
                </el-date-picker>
              </div>

              <!-- 月 -->
              <div v-if="dateType == 4">
                <el-date-picker
                  v-model="dateTime"
                  type="month"
                  size="small"
                  value-format="yyyy-MM"
                  :picker-options="pickerOption"
                  placeholder="选择月份"
                  :clearable="false">
                </el-date-picker>
              </div>

              <!-- 年 -->
              <div v-if="dateType == 5">
                <el-date-picker
                  v-model="dateTime"
                  type="year"
                  size="small"
                  value-format="yyyy"
                  :picker-options="pickerOption"
                  placeholder="选择年份"
                  :clearable="false">
                </el-date-picker>
              </div>

            </div>

            <div class="search-right">

              <!-- 时间类型 -->
              <div class="search-tabs">
                <el-radio
                  v-model="dateType"
                  v-for="(item, index) in dateTypeList"
                  :key="index"
                  :label="item.label"
                  :disabled="item.disable"
                  >{{ item.value }}
                </el-radio>
              </div>

              <!-- 搜索按钮 -->
              <div class="searcg-btns">
                <el-button
                  type="primary"
                  size="small"
                  icon="el-icon-search"
                  @click="search">
                  搜 索
                </el-button>
              </div>

            </div>

          </div>
          <div class="thCellWrap">
	          <!-- 表格内容 -->
	          <avue-crud
	            v-if="isTableShow"
	            :option="option"
	            :table-loading="loading"
	            :data="data"
	            :permission="permissionList"
	            v-model="form"
	            ref="crud"
	            @search-change="searchChange"
	            @search-reset="searchReset"
	            @selection-change="selectionChange"
	            @refresh-change="refreshChange"
	          >
	            <template slot="menuLeft">
	              <el-button
	                type="warning"
	                size="small"
	                plain
	                icon="el-icon-download"
	                @click="handleExport"
	                v-if="this.permission.loam_countreport_export">
	                导出
	              </el-button>
	            </template>
	          </avue-crud>
          </div>

        </basic-container>
      </el-col>
    </el-row>
  </div>
</template>

<script>
import {getReportHead,getList,toExport} from "@/api/loam/countreport";
import { mapGetters } from "vuex";
import website from "@/config/website";
import { getToken } from "@/util/auth";
import lcTree from "@/components/common/tree.vue";
import overlay from "@/components/common/overlay.vue";

export default {
  components: {
    lcTree, 
    overlay
  },
  data() {
    let _this = this;
    return {
      isTableShow: true,
      leftWidth: this.$leftWidth,
      rightWidth: this.$rightWidth,
      form: {},
      query: {},
      loading: false,
      page: {
        pageSize: 10,
        currentPage: 1,
        total: 0
      },
      selectionList: [],
      option: {
        menu: false,
        addBtn: false,
        calcHeight: 30,
        tip: false,
        printBtn: true,
        searchShow: true,
        searchMenuSpan: 6,
        border: true,
        index: true,
        dialogClickModal: false,
        selection: false,
        column: [{}]
      },
      data: [],
      nodeId: null,
      deptInfoName: "",
      deptInfoId: "",
      dateType: 2,
      dateTime: new Date().format("yyyy-MM-dd hh:mm:ss"),
      hourTime: "00:00",
      dateTypeList: [
        {
          label: 2,
          value: "日"
        },
        {
          label: 3,
          value: "周"
        },
        {
          label: 4,
          value: "月"
        },
        {
          label: 5,
          value: "年"
        }
      ],
      pickerOption: {
        firstDayOfWeek: 1,
        disabledDate(time) {
          return _this.dateType == 3 ? false : time.getTime() > Date.now();
        }
      },
      DATE_LABEL: "日期",
      HOUR_SECOND: 1 * 60 * 60,
      factorList: [],
      loamHead: {
        "ganRunTime": "fanWorkingTime",
        "purifierRunTime": "purifierWorkingTime",
        "linkRunTime": "fanPurifierWorkingTime",
        "linkRatio": "linkageRatio",
        "workTime": "workingTime",
        "standardRate": "standardRate"
      },
      factorHead: {
        "standardTime": "standardTime",
        "standardRadio": "standardRate",
        "minConc": "minVal",
        "maxConc": "maxVal",
        "purifyAvgConc": "purifiedAvgVal",
        "unpurifyAvgConc": "nonPurifiedAvgVal",
        "avgValue": "avgVal",
        "avgConc":"avgConc"
      }
    };
  },
  computed: {
    ...mapGetters(["permission"]),

    // 打印权限
    permissionList() {
      return {
        printBtn: this.vaildData(
          this.permission.loam_countreport_print,
          false
        )
      };
    }
  },
  watch: {

    // 时间类型
    dateType() {
      this.dateTime = new Date().format("yyyy-MM-dd hh:mm:ss");
      this.page.currentPage = 1;
      this.onLoad(this.page);
    }
  },
  methods: {

    // 左侧树加载事件
    ready(data) {
      this.nodeId = data.key;
      this.deptInfoName = data.title;
      this.deptInfoId = data.key;
      this.getTableHead(data.key).then(() => {
        this.onLoad(this.page);
      });
    },

    // 导出报表
    handleExport() {
      this.$confirm("是否导出报表数据?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(() => {
        let myDate = null;
        switch (this.dateType) {
          case 1: // 时
            myDate =
              this.dateTime.slice(0, 10) + " " + this.hourTime.slice(0, 2);
            break;
          case 2: // 日
            myDate = this.dateTime.slice(0, 10);
            break;
          case 3: // 周
            myDate = this.dateTime.slice(0, 10);
            break;
          case 4: // 月
            myDate = this.dateTime.slice(0, 7);
            break;
          case 5: // 年
            myDate = this.dateTime.slice(0, 4);
            break;

          default:
            myDate = this.dateTime;
            break;
        }
        window.open(
          `api/squirrel-loam/statreport/export?${
            this.website.tokenHeader
          }=${getToken()}&treeId=${this.nodeId}&type=${
            this.dateType
          }&time=${myDate}`
        );
      });
    },

    // 左侧树收缩、展开
    changeTreeBox() {
      this.leftWidth = this.leftWidth == this.$leftWidth ? 0 : this.$leftWidth
      this.rightWidth = this.rightWidth == this.$rightWidth ? 24 : this.$rightWidth
    },

    // 搜索
    search() {
      this.page.currentPage = 1;
      this.onLoad(this.page);
    },

    // 获取表头数据
    getTableHead(nodeId) {
      let _this = this;
      return new Promise(function(resolve, reject) {
        getReportHead(nodeId).then(res => {
          if (res.data.success) {
            if (res.data.data.length == 0) {
              _this.isTableShow = false;
              return;
            } else {
              _this.isTableShow = true;
            }

            // 封装表头
            let tableHead = res.data.data.length
              ? [{
                  label: _this.DATE_LABEL,
                  prop: "statTime",
                  align: "center",
                  fixed: "left",
                  overHidden: true,
                  width: 150
                }]
              : [];

            // 1.插入没有children的表头
            res.data.data.forEach(item => {
              if (item.value !== _this.DATE_LABEL && item.children.length === 0) {
                tableHead.push({
                  label: item.value,
                  align: "center",
                  prop: _this.loamHead[item.id],
                  width: 150
                });
              }
            });

            // 2.插入有children的表头（因子）
            res.data.data.forEach(item => {
              if (item.value !== _this.DATE_LABEL && item.children.length > 0) {
                var this_head = {
                  label: item.value,
                  align: "center",
                  factorCode: item.children[0].id.split("_")[1],
                  children: []
                };
                item.children.forEach(child => {
                  this_head.children.push({
                    label: child.value,
                    align: "center",
                    prop: _this.factorHead[child.id.split("_")[0]] + "_" + child.id.split("_")[1],
                    width: 120
                  });
                });
                tableHead.push(this_head);
                _this.factorList.push(this_head);
              }
            });

            // 将表头放入option
            _this.option.column = tableHead;
            resolve();
          } else {
            reject("网络拥堵，请退出重试");
          }
        });
      });
    },

    // 清空搜索条件
    searchReset() {
      this.query = {};
      this.onLoad(this.page);
    },

    // 点击搜索事件
    searchChange(params, done) {
      this.query = params;
      this.page.currentPage = 1;
      this.onLoad(this.page, params);
      done();
    },

    // 选项改变事件
    selectionChange(list) {
      this.selectionList = list;
    },

    // 清空选项
    selectionClear() {
      this.selectionList = [];
      this.$refs.crud.toggleSelection();
    },

    // 切换页面
    currentChange(currentPage) {
      this.page.currentPage = currentPage;
    },

    // 更换每页显示数据数量
    sizeChange(pageSize) {
      this.page.pageSize = pageSize;
    },

    // 刷新页面
    refreshChange() {
      this.onLoad(this.page, this.query);
    },

    // 获取表格内容
    onLoad(page, params = {}) {
      this.loading = true;

      if (this.nodeId) {
        let myDate = null;
        switch (this.dateType) {
          case 1: // 时
            myDate =
              this.dateTime.slice(0, 10) + " " + this.hourTime.slice(0, 2);
            break;
          case 2: // 日
            myDate = this.dateTime.slice(0, 10);
            break;
          case 3: // 周
            myDate = this.dateTime.slice(0, 10);
            break;
          case 4: // 月
            myDate = this.dateTime.slice(0, 7);
            break;
          case 5: // 年
            myDate = this.dateTime.slice(0, 4);
            break;

          default:
            myDate = this.dateTime;
            break;
        }
        getList(this.nodeId,this.dateType,myDate,Object.assign(params, this.query)).then(res => {
          const data = res.data.data;
          if (data) {
            this.data = [];
            data.forEach(item => {

              // 点位时间的值
              let obj = {
                // 日期
                statTime: item.statTime.replace(/T/g," "),
                // 风机运转时间
                fanWorkingTime: this.formatHourTime(item, "fanWorkingTime"), 
                // 净化器运转时间
                purifierWorkingTime: this.formatHourTime(item, "purifierWorkingTime"),
                // 联动运转时间
                fanPurifierWorkingTime: this.formatHourTime(item, "fanPurifierWorkingTime"),
                // 联动比
                linkageRatio: item.linkageRatio !== undefined && item.linkageRatio !== null && item.linkageRatio !== "" && item.linkageRatio >= 0 ? this.formatNumber(item.linkageRatio) : "-", 
                // 工作时间
                workingTime: this.formatHourTime(item, "workingTime"),
                standardRate: item.standardRate
              };

              // 根据表头的因子列表给所有因子一个默认值'-'
              this.factorList.forEach(factor => {
                obj[`standardTime_${factor.factorCode}`] = "-";
                obj[`standardRate_${factor.factorCode}`] = "-";
                obj[`minVal_${factor.factorCode}`] = "-";
                obj[`maxVal_${factor.factorCode}`] = "-";
                obj[`purifiedAvgVal_${factor.factorCode}`] = "-";
                obj[`nonPurifiedAvgVal_${factor.factorCode}`] = "-";
                obj[`avgVal_${factor.factorCode}`] = "-";
                obj[`avgConc_${factor.factorCode}`] = "-";
              });

              // 因子的值
              item.factorList.forEach(el => {
                obj[`standardTime_${el.factorCode}`] = this.formatHourTime(el, "standardTime");
                obj[`standardRate_${el.factorCode}`] = el.standardRate;
                obj[`minVal_${el.factorCode}`] = el.minVal;
                obj[`maxVal_${el.factorCode}`] = el.maxVal;
                obj[`purifiedAvgVal_${el.factorCode}`] = el.purifiedAvgVal;
                obj[`nonPurifiedAvgVal_${el.factorCode}`] = el.nonPurifiedAvgVal;
                obj[`avgVal_${el.factorCode}`] = el.avgVal;
                obj[`avgConc_${el.factorCode}`] = el.avgVal;
              });

              this.data.push(obj);
            });
          }
          this.loading = false;
          this.selectionClear();
        });
      }
    },

    // 保留两位小数并四舍五入
    formatNumber(data) {
      if ((data + "").indexOf(".") < 0)
        return data;
      else
        return parseFloat(data).toFixed(2);
    },

    // 转化时间为小时
    formatHourTime(item, param) {
      if(item[param] !== undefined && item[param] !== null && item[param] !== "" && item[param] >= 0) {
        return this.formatNumber(item[param] / this.HOUR_SECOND);
      }
      return "-";
    }

  }
};
</script>

<style lang="scss">
.CountreportTabel {
  .el-table__empty-block {
    width: 100% !important;
  }

  .avue-crud__menu {
    margin-bottom: $avue-tabel-menu-btn_margin_bottom;
  }

  .search-tools {
    padding-left: 0 !important;
    height: auto !important;
    margin-bottom: $common_margin_input_bottom;
  }

  .table-wrapper {
    .el-card__body {
      height: calc(100% - 35px);

      .avue-crud {
        height: calc(100% - 155px);
      }
    }

    .el-table__fixed {
      height: calc(100% - 12px) !important;
    }

    .el-table__fixed-right {
      height: calc(100% - 12px) !important;
    }
  }
}
</style>

<style lang="scss" scoped>
.map {
  width: 100%;
  height: 500px;
}

.box {
  height: 100%;
  margin-bottom: 0;
}

.el-row {
  height: calc(100% - 20px);
}

.el-col {
  height: 100%;
  overflow: auto;
}

.search-tools {
  height: 49px;
  display: flex;
  justify-content: space-between;
  padding: 0 8px;
}

.search-right {
  display: flex;
}

.search-tabs {
  height: 33px;
  display: flex;
  align-items: center;
  margin-right: 40px;
}

.overlay {
  position: absolute;
  width: 200px;
  height: 100%;
  opacity: 0;
  display: flex;
  align-items: center;
  padding-left: 6px;

  .tree-tool {
    height: 34px;
    width: 18px;
    background: #fff;
    box-shadow: 2px 1px 4px #ccc;
    border-top-right-radius: 3px;
    border-bottom-right-radius: 3px;
    cursor: pointer;
    display: flex;
    padding: 6px 0;
    z-index: 9999;

    .tool-line {
      margin-left: 3px;
      height: 100%;
      border-left: 1px solid #ddd;
    }
  }
}

.overlay:hover {
  opacity: 1;
}
</style>
